const express = require('express')
// multer处理文件上传的中间件
const multer = require('multer')
const { UPLOAD_PATH } = require('../utils/constant')
const Result = require('../models/Result')
const Book = require('../models/Book')
const boom = require('boom')
const { decoded } = require('../utils')
const bookServices = require('../services/book')

const router = express.Router()

// 定义图书上传的API
router.post(
	'/upload',
	multer({ dest: `${UPLOAD_PATH}/book` }).single('file'),
	function(req, res, next) {
		if(!req.file || req.file.length === 0) {
			new Result('上传电子书失败').fail(res)
		} else {
			const book = new Book(req.file)
			book.parse()
				.then(book => {
					console.log('book', book)
					new Result(book, '上传电子书成功').success(res)
				})
				.catch(err => {
					next(boom.badImplementation(err))
				})
		}
	}
)

router.post(
	'/create',
	function(req, res, next) {
		const decode = decoded(req)
		if(decode && decode.username) {
			// 获取用户名
			req.body.username = decode.username
		}
		const book = new Book(null, req.body)
		// console.log('bookSS' ,book)
		bookServices.insertBook(book).then(() => {
			new Result('添加电子书成功').success(res)
		}).catch(err => {
			next(boom.badImplementation(err))
		})
	}
)

router.post(
	'/update',
	function(req, res, next) {
		const decode = decoded(req)
		if(decode && decode.username) {
			// 获取用户名
			req.body.username = decode.username
		}
		// console.log('SSSS', req.body)
		const book = new Book(null, req.body)
		// console.log('bookSS' ,book)
		bookServices.updateBook(book).then(() => {
			new Result('更新电子书成功').success(res)
		}).catch(err => {
			next(boom.badImplementation(err))
		})
	}
)

router.get('/get', function(req, res, next) {
	const { fileName } = req.query
	if (!fileName) {
		next(boom.badRequest('参会fileName不能为空'))
	} else {
		bookServices.getBook(fileName).then(book => {
			new Result(book, '获取读书信息成功').success(res)
		}).catch(err => {
			next(boom.badImplementation(err))
		})
	}
})

router.get('/category', function(req, res, next) {
	bookServices.getCategory().then(category => {
		new Result(category, '获取分类成功').success(res)
	}).catch(err => {
		next(boom.badImplementation(err))
	})
})

router.get('/list', function(req, res, next) {
	bookServices.listBook(req.query).then(({ list, count, page, pageSize }) => {
		new Result({ list, count, page: +page, pageSize: +pageSize }, '获取图书列表成功').success(res)
	}).catch(err => {
		next(boom.badImplementation(err))
	})
})

// 删除图书的接口
router.get('/delete', function(req, res, next) {
	const { fileName } = req.query
	if (!fileName) {
		next(boom.badRequest('参会fileName不能为空'))
	} else {
		bookServices.deleteBook(fileName).then(() => {
			new Result('获取读书信息成功').success(res)
		}).catch(err => {
			next(boom.badImplementation(err))
		})
	}
})

module.exports = router